package com.aixin.project.db;

import com.aixin.project.data.CourseOrder;
import com.aixin.project.util.DBUtil;
import org.apache.commons.dbutils.QueryRunner;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Sufeng
 * Date: 12-4-17
 * Time: 下午7:47
 * To change this template use File | Settings | File Templates.
 */
public class CourseOrderDao extends Dao{
    public static CourseOrder find(long coid){
        return (CourseOrder) find("select * from courseorder where id=?",CourseOrder.class,coid);
    }
    
    
    public static CourseOrder find(long cid,long uid){
        return (CourseOrder) find("select * from courseorder where courseid=? and userid=? order by id desc limit 1",CourseOrder.class,cid,uid);
    }

    public static List<CourseOrder> listPagenation(int page,int psize,int status){
        int start = (page-1)*psize;
        StringBuffer sql = new StringBuffer("select * from courseorder");
        if(status!=-1)
            sql.append(" where status=").append(status);
        sql.append(" order by id desc limit ?,?");
        System.out.println(sql.toString());
        return list(sql.toString(),CourseOrder.class,start,psize);
    }
    
    public static long count(int status){
        String sql = "select count(*) c from courseorder";
        if(status!=-1)
            sql += " where status="+status;
        return  (Long)findBy(sql, "c", null);
    }

    public static int pointCount(long uid, long courseid){
        String sql = "select sum(point) as s from courseorder where status=1 and userid=? and courseid=?";
        return ((Long)findBy(sql,1,uid,courseid)).intValue();
    }
    
    public static long insert(CourseOrder courseOrder){
        return insert("insert into courseorder(porderid,userid,courseid,exportid,point,price) values(?,?,?,?,?,?)",
                courseOrder.getPorderid(),courseOrder.getUserid(),courseOrder.getCourseid(),courseOrder.getExportid(),courseOrder.getPoint(),courseOrder.getPrice());
    }
    
    public static int update(CourseOrder order){
        return update("update courseorder set point=?,price=? where courseid=? and userid=?", order.getPoint(),order.getPrice(),order.getCourseid(),order.getUserid());
    }
    /**
     * create course order, need transaction support
     * @param courseOrderer
     * @return order id
     */
    public static long create(CourseOrder courseOrderer) {
        try {
            DBUtil.startTransaction();
            Connection con = DBUtil.getContainer().get();
            QueryRunner run = new QueryRunner();
            run.update("insert into courseorder values(?,?)",1,2);
            DBUtil.commit();
        } catch (SQLException e) {
            DBUtil.rollback();
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return -1;
    }
}
